/**
 * 
 */
package cc.monggo.web.filter.response;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;


/**
 * @author fangjinsong
 *
 */
public class ServletOutputStreamResponseWrapper extends HttpServletResponseWrapper {
	private ServletOutputStream outputStream;// 打印机
	private ByteArrayOutputStream buffer;//缓冲区
	public ServletOutputStreamResponseWrapper(HttpServletResponse response,ByteArrayOutputStream buffer) {
		super(response);
		this.buffer = buffer;
	}
	
	@Override
	public void flushBuffer() throws IOException {
		outputStream.flush();
	}

	public void reset() {
		buffer.reset();
	}

	@Override
	public ServletOutputStream getOutputStream() throws IOException {
		if(outputStream==null){
			outputStream = new SimpleServletOutputStream(buffer);
		}
		return outputStream;
	}
	
}

class SimpleServletOutputStream extends ServletOutputStream{
	private ByteArrayOutputStream buffer;
	public SimpleServletOutputStream(ByteArrayOutputStream buffer){
		this.buffer = buffer;
	}
	/**
	 * 必须继续父类的抽象方法write，该方法来做OutputStream基类
	 */
	@Override
	public void write(int b) throws IOException {
		buffer.write(b);
	}
}
